<template>
  <Card :bordered="false" dis-hover>
    <Modal
      v-model="modalStatus"
      :loading="modalLoading"
      :title="modalTitle"
      width="800"
      @on-ok="handlerSave"
    >
      <Form ref="add_form" :model="record_a" show-message :rules="add_rules" :label-width="100">
        <FormItem label="标题：" prop="name">
          <Input v-model="record_a.name" placeholder="请输入菜单标题" clearable></Input>
        </FormItem>
        <FormItem label="路径：" prop="url">
          <Input v-model="record_a.url" placeholder="请输入菜单路径" clearable></Input>
        </FormItem>
        <FormItem label="图标：" prop="iconPath">
          <Icon-select :icon-all="iconAll" :prefix="record_a.iconPath" @selectIcon="record_a.iconPath = $event"></Icon-select>
        </FormItem>
        <!-- <FormItem label="是否页面：">
          <i-switch :value="record_a.pageFlag=='Y'" @on-change="(e)=>{record_a.pageFlag=e?'Y':'N'}">
            <Icon type="md-checkmark" slot="open"></Icon>
            <Icon type="md-close" slot="close"></Icon>
          </i-switch>
        </FormItem> -->
      </Form>
    </Modal>
    <Modal
      v-model="buttonStatus"
      :loading="buttonLoading"
      :title="buttonTitle"
      width="800"
      @on-ok="handlerSaveButton"
    >
      <Form ref="button_form" :model="record_button" show-message :rules="button_rules" :label-width="100">
        <FormItem label="按钮Key：" prop="buttonKey">
          <Input v-model="record_button.buttonKey" placeholder="请输入按钮Key" :disabled="isEdit" :clearable="!isEdit"></Input>
        </FormItem>
        <FormItem label="按钮名称：" prop="buttonName">
          <Input v-model="record_button.buttonName" placeholder="请输入按钮名称" clearable></Input>
        </FormItem>
      </Form>
    </Modal>
    <Row>
      <Col :xs="24" :sm="24" :md="24" :lg="6">
        <Card style="background: #fff;" :bordered="false" dis-hover>
          <div slot="title">
            <Dropdown style="margin-right: 14px;" @on-click="addRouters" v-if="pageButton.includes('add_menu')">
              <Button type="primary" ghost>
                添加菜单
                <Icon type="ios-arrow-down"></Icon>
              </Button>
              <DropdownMenu slot="list">
                <DropdownItem :name="0">添加顶栏菜单</DropdownItem>
                <DropdownItem :name="1" :disabled="!record_b.title">添加子菜单</DropdownItem>
              </DropdownMenu>
            </Dropdown>
            <Button style="margin-right: 14px;" type="primary" ghost icon="md-list" @click="exchangeTree">{{treeOpenTitle}}</Button>
            <!-- <ButtonGroup>
              <Button type="primary" ghost @click="moveMenu('up')" :disabled="!record_b.isFir">上移</Button>
              <Button type="primary" ghost @click="moveMenu('down')" :disabled="!record_b.isLat">下移</Button>
            </ButtonGroup> -->
          </div>
          <Spin v-if="loading" fix></Spin>
          <Tree :data="modelList" :render="renderContent" @on-select-change="selectTreeNode" @on-contextmenu="contextData = $event">
            <template slot="contextMenu">
                <DropdownItem @click.native="handleContextMenuEdit" v-if="pageButton.includes('edit_menu')">编辑</DropdownItem>
                <DropdownItem v-if="!contextData.parentId && pageButton.includes('add_menu')" @click.native="addRouters(3)">添加子菜单</DropdownItem>
                <DropdownItem @click.native="handleContextMenuDelete" style="color: #ed4014" v-if="pageButton.includes('delete_menu')">删除</DropdownItem>
            </template>
          </Tree>
        </Card>
      </Col>
      <Col min-hidden :xs="24" :sm="24" :md="24" :lg="18">
        <Card style="background: #fff;" :bordered="false" dis-hover>
          <div slot="title">
            <Avatar icon="md-apps" size="24" style="color: rgb(24, 144, 255);background-color: rgb(230, 247, 255);" />
            编辑菜单
          </div>
          <Form v-if="record_b.title" :model="record" :label-width="100">
            <FormItem label="标题：">
              <Input v-model="record.name" placeholder="请输入菜单标题"></Input>
            </FormItem>
            <FormItem label="路径：">
              <Input v-model="record.url" placeholder="请输入菜单路径"></Input>
            </FormItem>
            <FormItem label="图标：">
              <Icon-select :icon-all="iconAll" :prefix="record.iconPath" @selectIcon="record.iconPath = $event"></Icon-select>
            </FormItem>
            <!-- <FormItem label="是否页面：">
              <i-switch :value="record.pageFlag=='Y'" @on-change="(e)=>{record.pageFlag=e?'Y':'N'}">
                <Icon type="md-checkmark" slot="open"></Icon>
                <Icon type="md-close" slot="close"></Icon>
              </i-switch>
            </FormItem> -->
            <FormItem v-if="pageButton.includes('edit_menu')">
              <Button type="primary" @click="updateRouters" :loading="saveloading">保存修改</Button>&nbsp;&nbsp;&nbsp;
              <Button @click="resetBackUp">重置</Button>
            </FormItem>
              <Divider size="small">按钮配置</Divider>
              <div style="text-align: right">
                <Button type="primary" @click="addButtons" v-if="pageButton.includes('add_btn')">增加</Button>
              </div>
              <Table style="padding-top: 14px" :loading="buttonListLoading" :columns="columns" :data="buttonList">
                <template slot-scope="{ row, index }" slot="action">
                  <Button type="primary" style="margin-right: 8px" size="small" @click="addButtons(index, row)" ghost v-if="pageButton.includes('edit_btn')">编辑</Button>
                  <Button type="error" size="small" @click="doDeleteButton(index, row)" ghost v-if="pageButton.includes('delete_btn')">删除</Button>
                </template>
              </Table>
          </Form>
          <div v-else>
            <Alert>从菜单列表选择一项后，进行编辑</Alert>
          </div>
        </Card>
      </Col>
    </Row>
  </Card>
</template>
<script>
// import { getRouters, addRouters, updateRouters, removeRouters, getMenuButtons, addMenuButton, updateButton, deleteMenuButton, moveSeq } from "@/api/system/menu";
import { getRouters, addRouters, updateRouters, removeRouters, getMenuButtons, addMenuButton, updateButton, deleteMenuButton } from "@/api/menu";
import iconAll from "@/utils/iconAll";
import IconSelect from "@/components/icon-select";
export default {
  name: "menus",
  data() {
    return {
      loading: false,
      modelList: [],
      treeOpenStatus: true,
      saveloading: false,
      record_a: {},
      record_b: {},
      record: {},
      modalStatus: false,
      modalLoading: false,
      modalTitle: '',
      buttonStatus: false,
      buttonLoading: false,
      buttonTitle: '',
      isEdit: false,
      record_button: {},
      contextData: {},
      buttonList: [],
      buttonListLoading: false,
      columns: [
        {
          title: "",
          width: 100,
          align: "center",
          render: (h, params) => {
            return h("span", params.index + 1);
          }
        },
        {
          title: "按钮Key",
          key: "buttonKey"
        },
        {
          title: "按钮名称",
          key: "buttonName"
        }
      ],
      add_rules: {
        name: { required: true, message: '菜单标题不能为空', trigger: 'change,blur' },
        url: { required: true, message: '菜单路径不能为空', trigger: 'change,blur' },
        iconPath: { required: true, message: '请选择菜单Icon', trigger: 'change' }
      },
      button_rules: {
          buttonKey: { required: true, message: '按钮Key不能为空', trigger: 'change,blur' },
          buttonName: { required: true, message: '按钮名称不能为空', trigger: 'change,blur' }
      },
      flag: true
    };
  },
  created() {
    this.getMenu();
  },
  components: {
    IconSelect
  },
  computed: {
    treeOpenTitle() {
      return this.treeOpenStatus ? "全部收起" : "全部展开"
    },
    iconAll() {
      return iconAll
    },
    pageButton() {
      let pageButton = this.$store.state.router.pageButton;
      (pageButton.includes('edit_btn') || pageButton.includes('delete_btn')) && this.columns.push({
        title: "操作",
        minWidth: 140,
        slot: "action"
      })
      return pageButton;
    }
  },
  methods: {
    getMenu() {
      this.loading = true;
      getRouters().then(res=>{
        this.modelList = this.filterMenu(res.data);
      }).finally(()=>{this.loading = false})
    },
    getMenuButtons(id) {
      this.buttonListLoading = true;
      getMenuButtons({menuId: id}).then(res=>{
        this.buttonListLoading = false;
        this.buttonList = res.data;
      }).catch(()=>{this.buttonListLoading = false})
    },
    filterMenu(tree = []) {
      let arr = [];
      if (tree.length !== 0) {
        tree.forEach((item,index) => {
              let obj = item;
              obj.title = item.name;
              obj.expand = this.treeOpenStatus;
              obj.contextmenu = true;
              obj.isFir = !(index <= 0);
              obj.isLat = !(tree.length-1 <= index);
              obj.isOly = (item.children&&item.children.length) > 0;
              if(item.id == this.record_b.id) {
                this.record_b.isFir = !(index <= 0);
                this.record_b.isLat = !(tree.length-1 <= index);
              }
              obj.selected = obj.id == this.record.id;
              if (item.children && item.children.length != 0) {
                  obj.children = this.filterMenu(item.children);
              }
              arr.push(obj);
          });
      }
      return arr;
    },
    renderContent(h, { root, node, data }) {
      return h('span', [
        h('span', [ h('span', data.title) ]),
        h('span', [
          h('Button', {
            props: {
              icon: 'md-trash',
              disabled: data.isOly
            },
            style: {
              display: this.pageButton.includes('del_menu') ? 'inline-block' : 'none'
            },
            on: {
              click: (e) => {
                e.stopPropagation();
                this.deleteNode(data.id)
              }
            }
          })
        ])
      ]);
    },
    clearSelectMenu(tree = [], id) {
      let arr = [];
      if (tree.length !== 0) {
          tree.forEach(item => {
              let obj = item;
              obj.selected = obj.id == id;
              if (item.children && item.children.length != 0) {
                  obj.children = this.clearSelectMenu(item.children, id);
              }
              arr.push(obj);
          });
      }
      return arr;
    },
    exchangeTree() {
      this.modelList = this.treeChangeExpand(this.modelList, this.treeOpenStatus =! this.treeOpenStatus);
    },
    //递归给树设置expand
    treeChangeExpand(treeData, flag) {
      let _this = this;
      for (var i = 0; treeData && i < treeData.length; i++) {
        treeData[i].expand = flag;
        if (treeData[i].children) {
          treeData[i].children = _this.treeChangeExpand(treeData[i].children,flag);
        }
      }
      return treeData;
    },
    selectTreeNode(node) {
      if(node && node.length) {
        // 备份节点 用于重置
        this.record_b = JSON.parse(JSON.stringify(node[0]));
        this.record = JSON.parse(JSON.stringify(node[0]));
        this.getMenuButtons(this.record.id);
      } else {
        this.record_b = {};
        this.record = {};
      }
    },
    // 重置编辑中菜单
    resetBackUp() {
      this.record = JSON.parse(JSON.stringify(this.record_b));
    },
    updateRouters() {
      this.saveloading = true;
      updateRouters(this.record).then(res=>{
        this.$Message.success("修改成功");
        this.getMenu();
        this.record_b = JSON.parse(JSON.stringify(this.record));
      }).finally(()=>{this.saveloading=false})
    },
    addRouters(type) {
      this.record_a = {
        iconPath: "",
        name: "",
        parentId: 0,
        url: ""
      }
      this.$refs.add_form.resetFields();
      Boolean(type) && (this.record_a.parentId = type == 3 ? this.contextData.id : this.record.id);
      this.modalTitle = Boolean(type) ? "添加子菜单" : "添加顶栏菜单";
      this.modalStatus = true;
    },
    handlerSave() {
      this.$refs.add_form.validate((valid) => {
        if(valid) {
          addRouters(this.record_a).then(res=>{
            this.$Message.success("新增成功");
            this.getMenu();
          }).finally(()=>{this.modalStatus=false})
        } else {
          this.$Message.warning("校验未通过");
          this.modalLoading = false;
          this.$nextTick(() => {
            this.modalLoading = true;
          });
        }
      });
    },
    // 移动菜单
    // moveMenu(type) {
    //   if (!this.flag) return false;
    //   this.flag = false;
    //   moveSeq({
    //     id: this.record_b.id,
    //     oprType: type
    //   }).then(res=>{
    //     this.$Message.success("操作成功");
    //     this.getMenu();
    //   }).finally(()=>this.flag = true)
    // },
    handleContextMenuEdit() {
      this.modelList = this.clearSelectMenu(this.modelList, this.contextData.id);
      this.selectTreeNode([this.contextData])
    },
    handleContextMenuDelete() {
      if(this.contextData.children && this.contextData.children.length){
        this.$Message.error("请先删除下级节点");
        return false;
      }
      this.deleteNode(this.contextData.id)
    },
    deleteNode(id) {
      this.$Modal.confirm({
        title: "提示",
        content: "确定要删除当前菜单吗？",
        onOk: () => {
          removeRouters({id}).then(res=>{
            this.$Message.success("删除成功");
            this.getMenu();
            this.selectTreeNode();
          })
        },
      });
    },
    addButtons(index, row) {
      this.$refs.button_form.resetFields();
      this.buttonStatus = true;
      this.buttonTitle = row ? "编辑按钮" : "新增按钮"
      this.isEdit = row ? true : false;
      this.record_button = {
        id: row?.id,
        menuId: this.record.id,
        buttonKey: row ? row.buttonKey : "",
        buttonName: row ? row.buttonName : ""
      }
    },
    doDeleteButton(index, row) {
      this.$Modal.confirm({
        title: "提示",
        content: "确定要删除当前按钮吗？",
        onOk: () => {
          deleteMenuButton({
            menuId: this.record.id,
            buttonKey: row.buttonKey
          }).then(res=>{
            this.$Message.success("删除成功");
            this.getMenuButtons(this.record.id);
          })
        },
      });
    },
    handlerSaveButton() {
      this.$refs.button_form.validate((valid) => {
        if(valid) {
          let addOrUpDate = this.isEdit ? updateButton : addMenuButton;
          addOrUpDate(this.record_button).then(res=>{
            this.$Message.success(this.isEdit ? "修改成功" : "新增成功");
            this.getMenuButtons(this.record.id);
          }).finally(()=>this.buttonStatus = false)
        } else {
          this.$Message.warning("校验未通过");
          this.buttonLoading = false;
          this.$nextTick(() => {
            this.buttonLoading = true;
          });
        }
      });
    }
  }
};
</script>
<style lang="less" scoped>
/deep/ .ivu-card-body {
  background-color: #f5f7f9;
  padding: 0;
  .ivu-row {
    height: 100%;
    > div {
    height: 100%;
      padding: 0 12px;
      .ivu-card-body {
        background-color: #fff;
        padding: 16px;
      }
      > div {
        height: 100%;
        overflow: hidden;
        display: flex;
        flex-wrap: wrap;
        flex-direction: column;
        .ivu-card-body {
          flex: 1;
          overflow: auto;
          position: relative;
        }
      }
    }
  }
}
/deep/.ivu-tree ul li > span:nth-of-type(2){
  width: 100%;
  padding-right: 20px;
  > span span:nth-of-type(2) {
    float: right;
    button {
      margin-left: 6px;
      font-size: 10px;
      height: 20px;
      width: 24px;
    }
  }
}
</style>